package com.getpebble.android.main.sections.mypebble.adapter;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.GridView;
import android.widget.TextView;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.framework.util.UiUtil;
import com.getpebble.android.common.framework.widget.AsyncImageView;
import com.getpebble.android.common.model.LockerApp;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.provider.model.PblInstalledJoinLockerAppDataModel;
import com.getpebble.android.main.sections.mypebble.fragment.LoadUnloadDialogFragment;
import com.getpebble.android.util.HttpUtils;
import com.getpebble.android.widget.PblTextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LockerAppsPagerAdapter extends PagerAdapter implements LoaderCallbacks<Cursor> {
    private static final String TAG = LockerAppsPagerAdapter.class.getSimpleName();
    private List<WatchAppGridViewAdapter> mAdapters = new ArrayList();
    private int mAppIconHeight;
    private int mAppIconWidth;
    private Context mContext;
    private Cursor mCursor = null;
    private FragmentManager mFragmentManager;
    private LoaderManager mLoaderManager;

    private static class ViewHolder {
        AsyncImageView imageView;
        int position;
        PblTextView textView;

        private ViewHolder() {
            this.position = -1;
        }
    }

    private class WatchAppGridViewAdapter extends CursorAdapter {
        private LayoutInflater mLayoutInflater;
        private int mPosition;
        private HashMap<Integer, LockerApp> mWatchAppHashMap = new HashMap();

        @SuppressLint({"UseSparseArrays"})
        public WatchAppGridViewAdapter(Context context, Cursor cursor, int position) {
            super(context, cursor, 2);
            this.mPosition = position;
            this.mLayoutInflater = LayoutInflater.from(context);
        }

        protected void onContentChanged() {
            super.onContentChanged();
            LockerAppsPagerAdapter.this.updateAllAdapterCursors();
        }

        public Cursor swapCursor(Cursor newCursor) {
            this.mWatchAppHashMap.clear();
            return super.swapCursor(newCursor);
        }

        private LockerApp getWatchApp(int position) {
            if (this.mWatchAppHashMap.containsKey(Integer.valueOf(position))) {
                return (LockerApp) this.mWatchAppHashMap.get(Integer.valueOf(position));
            }
            ContentValues contentValues = new ContentValues();
            DatabaseUtils.cursorRowToContentValues(getCursor(), contentValues);
            LockerApp lockerApp = LockerApp.fromContentValues(contentValues);
            this.mWatchAppHashMap.put(Integer.valueOf(position), lockerApp);
            return lockerApp;
        }

        public void bindView(View view, final Context context, Cursor cursor) {
            final LockerApp lockerApp = getWatchApp(getCursor().getPosition());
            if (lockerApp == null) {
                Trace.error(LockerAppsPagerAdapter.TAG, "Unable to get WatchApp for position: " + getCursor().getPosition());
                return;
            }
            ViewHolder viewHolder = (ViewHolder) view.getTag();
            viewHolder.textView.setText(lockerApp.getAppName().toUpperCase());
            AsyncImageView imageView = viewHolder.imageView;
            imageView.getLayoutParams().height = LockerAppsPagerAdapter.this.mAppIconHeight;
            String url = lockerApp.getScreenshotImage();
            if (url != null) {
                imageView.fetch(url);
            }
            view.getLayoutParams().width = LockerAppsPagerAdapter.this.mAppIconWidth;
            viewHolder.position = cursor.getPosition();
            view.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    LoadUnloadDialogFragment dialogFragment = new LoadUnloadDialogFragment();
                    PblDevice device = PebbleApplication.getConnectedDevice();
                    boolean isPebbleFull = false;
                    if (!(context == null || device == null)) {
                        Cursor cursor = PblInstalledJoinLockerAppDataModel.fetchAppsCursor(context.getContentResolver(), device);
                        if (cursor != null) {
                            isPebbleFull = cursor.getCount() == 8;
                            cursor.close();
                        }
                    }
                    dialogFragment.setIsPebbleFull(isPebbleFull);
                    dialogFragment.setWatchApp(lockerApp);
                    dialogFragment.show(LockerAppsPagerAdapter.this.mFragmentManager, lockerApp.getAppName());
                }
            });
        }

        private void bindEmptyView(View view, int position) {
            ViewHolder viewHolder = (ViewHolder) view.getTag();
            viewHolder.textView.setText(null);
            AsyncImageView imageView = viewHolder.imageView;
            imageView.setImageResource(17301579);
            imageView.getLayoutParams().height = LockerAppsPagerAdapter.this.mAppIconHeight;
            view.getLayoutParams().width = LockerAppsPagerAdapter.this.mAppIconWidth;
            viewHolder.position = position;
        }

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = this.mLayoutInflater.inflate(R.layout.watchapp_grid_item, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.textView = (PblTextView) view.findViewById(R.id.txt_watchapp_grid_item_name);
            viewHolder.imageView = (AsyncImageView) view.findViewById(R.id.watchapp_grid_item_img);
            view.setTag(viewHolder);
            return view;
        }

        public int getCount() {
            return getEndIndex() - getStartIndex();
        }

        private int getStartIndex() {
            return this.mPosition * 6;
        }

        private int getEndIndex() {
            int count = getCursor() != null ? getCursor().getCount() : 0;
            int end = (this.mPosition + 1) * 6;
            if (end > count) {
                return (count % 6) + getStartIndex();
            }
            return end;
        }

        private int getRealPosition(int position) {
            return getStartIndex() + position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            boolean canBindView = true;
            if (getCursor().isClosed()) {
                Trace.warning(LockerAppsPagerAdapter.TAG, "Cannot bindView: Cursor is closed.");
                canBindView = false;
            } else if (!getCursor().moveToPosition(getRealPosition(position))) {
                Trace.warning(LockerAppsPagerAdapter.TAG, "Cannot bindView: Real position is not in cursor bounds.");
                canBindView = false;
            }
            if (convertView == null) {
                convertView = newView(LockerAppsPagerAdapter.this.getContext(), getCursor(), parent);
            }
            if (canBindView) {
                bindView(convertView, LockerAppsPagerAdapter.this.getContext(), getCursor());
            } else {
                Trace.debug(LockerAppsPagerAdapter.TAG, "Binding empty view");
                bindEmptyView(convertView, position);
            }
            return convertView;
        }
    }

    public LockerAppsPagerAdapter(Context context, LoaderManager loaderManager, FragmentManager fragmentManager) {
        this.mContext = context;
        this.mLoaderManager = loaderManager;
        this.mLoaderManager.initLoader(0, null, this);
        this.mFragmentManager = fragmentManager;
        calculateAppIconsSize();
    }

    public Context getContext() {
        return this.mContext;
    }

    public void onConnectedDeviceUpdated() {
        Trace.debug(TAG, "Restarting the loader");
        this.mLoaderManager.restartLoader(0, null, this);
    }

    public int getCount() {
        if (this.mCursor == null || this.mCursor.isClosed()) {
            return 0;
        }
        if (this.mCursor.getCount() == 0) {
            return 1;
        }
        int count = this.mCursor.getCount() / 6;
        if (this.mCursor.getCount() % 6 != 0) {
            return count + 1;
        }
        return count;
    }

    public boolean isViewFromObject(View view, Object o) {
        return view.equals(o);
    }

    private WatchAppGridViewAdapter getAdapter(int position) {
        if (this.mAdapters.size() > position) {
            return (WatchAppGridViewAdapter) this.mAdapters.get(position);
        }
        return null;
    }

    private void updateAllAdapterCursors() {
        boolean dataChanged = false;
        while (getCount() < this.mAdapters.size()) {
            Trace.debug(TAG, "Remove adapter at index: " + (this.mAdapters.size() - 1));
            this.mAdapters.remove(this.mAdapters.size() - 1);
            dataChanged = true;
        }
        for (int i = this.mAdapters.size(); i < getCount(); i++) {
            Trace.debug(TAG, "adding adapter at index: " + i);
            this.mAdapters.add(new WatchAppGridViewAdapter(getContext(), this.mCursor, i));
            dataChanged = true;
        }
        for (WatchAppGridViewAdapter adapter : this.mAdapters) {
            adapter.swapCursor(this.mCursor);
        }
        if (dataChanged) {
            notifyDataSetChanged();
        }
    }

    public Object instantiateItem(ViewGroup container, int position) {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        if (this.mCursor.getCount() == 0 && position == 0) {
            TextView lockerStatusText = (TextView) layoutInflater.inflate(R.layout.textview_locker_apps, container, false);
            if (lockerStatusText != null) {
                Context context = getContext();
                if (context == null) {
                    Trace.error(TAG, "instantiateItem: Context was null");
                    return null;
                } else if (HttpUtils.hasInternetConnection(context)) {
                    lockerStatusText.setText(context.getString(R.string.my_pebble_locker_no_apps));
                } else {
                    lockerStatusText.setText(context.getString(R.string.my_pebble_locker_no_network_connection));
                }
            }
            container.addView(lockerStatusText);
            return lockerStatusText;
        }
        View gridView = (GridView) layoutInflater.inflate(R.layout.gridview_locker_apps, container, false);
        if (gridView != null) {
            gridView.setAdapter(getAdapter(position));
            container.addView(gridView);
        }
        return gridView;
    }

    public int getItemPosition(Object object) {
        return -2;
    }

    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    private void calculateAppIconsSize() {
        this.mAppIconWidth = (UiUtil.getScreenWidth(getContext()) * 19) / 100;
        this.mAppIconHeight = (int) (((float) this.mAppIconWidth) / 0.85714287f);
    }

    public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) {
        switch (loaderId) {
            case R.styleable.WalletFragmentStyle_buyButtonHeight /*0*/:
                Trace.debug(TAG, "Creating watchapps loader");
                PblDevice pblDevice = PebbleApplication.getConnectedDevice();
                Trace.debug(TAG, "Setting device address to: " + (pblDevice == null ? "" : pblDevice.getAddress()));
                return new CursorLoader(getContext(), PblContentProviderUtil.getTableUri("locker_apps"), null, "_needs_delete = ? AND uuid NOT IN (SELECT uuid FROM installed_apps WHERE device_address = ?)", new String[]{"0", deviceAddress}, "_date_created DESC, _id DESC");
            default:
                Trace.error(TAG, "Invalid loader id: " + loaderId);
                return null;
        }
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        Trace.debug(TAG, "onLoadFinished");
        this.mCursor = cursor;
        updateAllAdapterCursors();
        notifyDataSetChanged();
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        this.mCursor = null;
        updateAllAdapterCursors();
        notifyDataSetChanged();
    }
}
